import { http } from "@kit.NetworkKit";

export class APIv5OrgOwner {
  id: number = 0;
  login: string = '';
  name: string = '';
  avatar_url: string = '';
  url: string = '';
  html_url: string = '';
  remark: string = '';
}

export class APIv5Org {
  avatar_url: string = '';
  created_at: string = '';
  description: string = '';
  email: string = '';
  enterprise: string = '';
  events_url: string = '';
  follow_count: number = 0;
  html_url: string = '';
  id: number = -1;
  location: string = '';
  login: string = '';
  members: number = 0;
  members_url: string = '';
  name: string = '';
  owner: APIv5OrgOwner = new APIv5OrgOwner();
  private_repos: number = 0;
  public: boolean = false;
  public_repos: number = 0;
  repos_url: string = '';
  type: string = '';
  url: string = '';
}

class CGiteeInfoUtils {
  ERR_FORBIDDEN = "forbidden"

  getOrgInfo(org: string = 'ohos_port'): Promise<APIv5Org> {
    return new Promise<APIv5Org>((resolve, reject) => {
      const client = http.createHttp();
      client.request(`https://gitee.com/api/v5/orgs/${org}`)
        .then(res => {
          if (res.responseCode != http.ResponseCode.OK) {
            if (res.responseCode == http.ResponseCode.FORBIDDEN) {
              reject(new Error(this.ERR_FORBIDDEN))
            }
            reject(new Error("Network error"));
            return;
          }
          try {
            const c: APIv5Org = JSON.parse(res.result.toString());
            resolve(c);
          } catch (e) {
            reject(e);
          }
        })
        .catch(err => {
          reject(err);
        })
        .finally(() => {
          client.destroy();
        })
    })
  }
}

export const GiteeInfoUtils = new CGiteeInfoUtils();